﻿
// registerDlg.cpp: 实现文件
//

#include "stdafx.h"
#include "register.h"
#include "registerDlg.h"
#include "afxdialogex.h"
#include "RegisterAPI.h"
#include "resource.h"
#include <Lm.h>
#pragma comment(lib, "Netapi32.lib")

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

bool queryCurrentUser(wchar_t *szBuffer);
BOOL IsAdmin();
BOOL IsUserInAdminGroup();

BOOL IsRunAsAdmin();

// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// 对话框数据
#ifdef AFX_DESIGN_TIME
	enum { IDD = IDD_ABOUTBOX };
#endif

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);  // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)

END_MESSAGE_MAP()


// CregisterDlg 对话框



CregisterDlg::CregisterDlg(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_REGISTER_DIALOG, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

/*
控件命令合理性
*/
void CregisterDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_SPECVALUE, m_edit_specvalue);
	DDX_Control(pDX, IDC_CURRENT_REGISTER_DATETIME, m_edit_datetime);
	DDX_Control(pDX, IDC_CURRENT_REGISTER_PCID, m_edit_pcid );
	DDX_Control(pDX, IDC_CURRENTUSER, m_edit_currentUser);
	DDX_Control(pDX, IDC_EDIT3, m_edit_isAdmin);
}

/*
*/
BEGIN_MESSAGE_MAP(CregisterDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_QUERYREGISTER, &CregisterDlg::OnBnClickedQueryregister)
	ON_BN_CLICKED(ID_REGISTER_CURRENT, &CregisterDlg::OnBnClickedRegisterCurrent)
	ON_BN_CLICKED(IDC_REGISTER2, &CregisterDlg::OnBnClickedRegister2)
	ON_BN_CLICKED(IDC_BUTTON3, &CregisterDlg::OnBnClickedButton3)
	ON_STN_CLICKED(IDC_LABEL, &CregisterDlg::OnStnClickedLabel)
END_MESSAGE_MAP()


// CregisterDlg 消息处理程序
/**
是否可以操作ui了？
*/
BOOL CregisterDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != nullptr)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	// TODO: 在此添加额外的初始化代码
	CString currentUser;
	wchar_t szBuffer[255];
	queryCurrentUser(szBuffer);
	m_edit_currentUser.SetWindowTextW(szBuffer);
	//IsAdmin()==TRUE? AfxMessageBox(_T("超级用户")):AfxMessageBox(_T("一般用户"));
	CString pcId;
	Register::getId(&pcId);
	m_edit_pcid.SetWindowTextW(pcId);
	CString registerDatetime;
	Register::getRegisterDatetime(&registerDatetime);
	m_edit_datetime.SetWindowTextW(registerDatetime);
	if (IsUserInAdminGroup()&& IsRunAsAdmin()) {
		//AfxMessageBox(_T("超级用户"));
		m_edit_isAdmin.SetWindowTextW(_T("超级用户"));
	}
	else {
		m_edit_isAdmin.SetWindowTextW(_T("普通用户"));
	}
	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

void CregisterDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CregisterDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CregisterDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

/**
*
*/
void CregisterDlg::OnBnClickedQueryregister()
{
	// TODO: 在此添加控件通知处理程序代码
	bool allowPrinter = false;
	allowPrinter = Register::queryRegister();
	if (allowPrinter == false) {
		//AfxMessageBox(_T("微软打印未注册,无法打印"));
		AfxMessageBox(_T("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"));
		return;
	}
	else {
		AfxMessageBox(_T("已注册"));
	}
}

/***
*
***/
void CregisterDlg::OnBnClickedRegisterCurrent()
{
	// TODO: 在此添加控件通知处理程序代码
	// TODO: 在此添加控件通知处理程序代码
	CDialogEx::OnOK();
	CString datetime;
	m_edit_specvalue.GetWindowTextW(datetime);
	bool retval = Register::setupRegRegister();
	if (retval) {
		AfxMessageBox(_T("建立键值成功"));
	}
	else {
		AfxMessageBox(_T("建立键值失败"));
	}
}


void CregisterDlg::OnBnClickedRegister2()
{
	// TODO: 在此添加控件通知处理程序代码
}



void CregisterDlg::OnBnClickedButton3()
{
	// TODO: 在此添加控件通知处理程序代码
	
	//Register::queryRegister();
	//AfxMessageBox(pcId);
}

/*
*/
bool queryCurrentUser(wchar_t *szBuffer)
{
	DWORD dwNameLen = 255;	
	memset(szBuffer, 0, dwNameLen );
	if (!GetUserName(szBuffer, &dwNameLen)) {
		//printf("Error %d\n", GetLastError());
		return false;
	}		
	else {
		//printf("当前用户名为：%ws\n", szBuffer);
		return true;
	}
	//getchar();
	
}

BOOL IsAdmin()
{
	HANDLE hAccessToken;
	BYTE * InfoBuffer = new BYTE[1024];
	PTOKEN_GROUPS ptgGroups;
	DWORD dwInfoBufferSize;
	PSID psidAdministrators;
	SID_IDENTIFIER_AUTHORITY siaNtAuthority = SECURITY_NT_AUTHORITY;

	/*
	*/
	if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hAccessToken))
	{
		delete InfoBuffer;
		return FALSE;
	}

	if (!GetTokenInformation(hAccessToken, TokenGroups, InfoBuffer, 1024, &dwInfoBufferSize))
	{
		delete InfoBuffer;
		CloseHandle(hAccessToken);
		return FALSE;
	}

	CloseHandle(hAccessToken);

	if (!AllocateAndInitializeSid(&siaNtAuthority,
		2,
		SECURITY_BUILTIN_DOMAIN_RID,
		DOMAIN_ALIAS_RID_ADMINS,
		0, 0, 0, 0, 0, 0,
		&psidAdministrators))
	{
		delete InfoBuffer;
		return FALSE;
	}

	ptgGroups = (PTOKEN_GROUPS)InfoBuffer;

	for (UINT i = 0; i < ptgGroups->GroupCount; i++)
	{
		if (EqualSid(psidAdministrators, ptgGroups->Groups[i].Sid))
		{
			FreeSid(psidAdministrators);
			delete InfoBuffer;
			return TRUE;
		}
	}
	return FALSE;
}

BOOL IsUserAdminPrivilege(const CString & strUserName, BOOL & bAdminPrivilege)
{
	bAdminPrivilege = FALSE;

	PSID pSid = NULL;
	DWORD cbSid = 0;
	LPTSTR bufDomain = NULL;
	DWORD cbDomain = 0;
	SID_NAME_USE type;
	LookupAccountName(NULL, strUserName, pSid, &cbSid, bufDomain, &cbDomain, &type);
	if (cbSid)
	{
		pSid = new byte[cbSid];
		bufDomain = new TCHAR[cbDomain];
		if (LookupAccountName(NULL, strUserName, pSid, &cbSid, bufDomain, &cbDomain, &type))
		{
			PSID_IDENTIFIER_AUTHORITY pAutho = GetSidIdentifierAuthority(pSid);
			DWORD dwErr = GetLastError();
			if (!dwErr)
			{
				SID_IDENTIFIER_AUTHORITY AdminAuth = SECURITY_NT_AUTHORITY;
				bAdminPrivilege = !memcmp(pAutho, &AdminAuth, sizeof(SID_IDENTIFIER_AUTHORITY));
			}
		}
		delete[]pSid;
		delete[]bufDomain;
	}
	if (bAdminPrivilege)
		return TRUE;

	DWORD rc;
	USER_INFO_1 *info;
	rc = NetUserGetInfo(NULL, _bstr_t(strUserName), 1, (byte**)&info);
	if (rc == NERR_Success)
	{
		bAdminPrivilege = info->usri1_priv == USER_PRIV_ADMIN;
		NetApiBufferFree(info);
	}

	return rc == NERR_Success;
}


void CregisterDlg::OnStnClickedLabel()
{
	// TODO: 在此添加控件通知处理程序代码
}

BOOL IsUserInAdminGroup() //判断是否在管理员组
{
	BOOL fInAdminGroup = FALSE;
	HANDLE hToken = NULL;
	HANDLE hTokenToCheck = NULL;
	DWORD cbSize = 0;

	OSVERSIONINFO osver = { 0 };
	osver.dwOSVersionInfoSize = sizeof(osver);

	if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_DUPLICATE, &hToken))
		goto Cleanup;
	if (!GetVersionEx(&osver))
		goto Cleanup;
	if (osver.dwMajorVersion >= 6)
	{
		TOKEN_ELEVATION_TYPE elevType;
		if (!GetTokenInformation(hToken, TokenElevationType, &elevType, sizeof(elevType), &cbSize))
			goto Cleanup;
		if (TokenElevationTypeLimited == elevType)
		{
			if (!GetTokenInformation(hToken, TokenLinkedToken, &hTokenToCheck, sizeof(hTokenToCheck), &cbSize))
				goto Cleanup;
		}
	}

	if (!hTokenToCheck)
	{
		if (!DuplicateToken(hToken, SecurityIdentification, &hTokenToCheck))
			goto Cleanup;
	}

	BYTE adminSID[SECURITY_MAX_SID_SIZE];
	cbSize = sizeof(adminSID);
	if (!CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, &adminSID, &cbSize))
		goto Cleanup;
	if (!CheckTokenMembership(hTokenToCheck, &adminSID, &fInAdminGroup))
		goto Cleanup;

Cleanup:
	if (hToken)    CloseHandle(hToken);
	if (hTokenToCheck) CloseHandle(hTokenToCheck);
	return fInAdminGroup;
}


BOOL IsRunAsAdmin() //判断是否以管理员权限运行
{
	BOOL fIsRunAsAdmin = FALSE;
	DWORD dwError = ERROR_SUCCESS;
	PSID pAdministratorsGroup = NULL;

	SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
	if (!AllocateAndInitializeSid(
		&NtAuthority,
		2,
		SECURITY_BUILTIN_DOMAIN_RID,
		DOMAIN_ALIAS_RID_ADMINS,
		0, 0, 0, 0, 0, 0,
		&pAdministratorsGroup))
	{
		dwError = GetLastError();
		goto Cleanup;
	}

	if (!CheckTokenMembership(NULL, pAdministratorsGroup, &fIsRunAsAdmin))
	{
		dwError = GetLastError();
		goto Cleanup;
	}

Cleanup:
	if (pAdministratorsGroup) FreeSid(pAdministratorsGroup);
	return fIsRunAsAdmin;
}
